package io.webfolder.cdp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import io.webfolder.cdp.exception.CdpException;

public class MacOsProcessManager extends ProcessManager {

	private int pid;

	private String cdp4jId;

	private CdpProcess process;

	public void setProcess(CdpProcess process) {
		if (this.process != null)
			throw new IllegalStateException();
		try {
			Field pidField = process.getProcess().getClass().getDeclaredField("pid");
			pidField.setAccessible(true);
			this.pid = ((Integer) pidField.get(process.getProcess())).intValue();
			this.process = process;
		} catch (Throwable e) {
			throw new CdpException(e);
		}
		this.cdp4jId = process.getCdp4jProcessId();
	}

	public boolean kill() {
		if (this.process == null)
			return false;
		ProcessBuilder builder = new ProcessBuilder(new String[] { "ps", "auxww" });
		boolean found = false;
		try {
			Process process = builder.start();
			BufferedReader scanner = new BufferedReader(new InputStreamReader(process.getInputStream()));
			try {
				String line = scanner.readLine();
				String processId = "cdp4jId=" + this.cdp4jId;
				String strPid = " " + String.valueOf(this.pid) + " ";
				while ((line = scanner.readLine()) != null) {
					if (line.contains(processId) && line.contains(strPid)) {
						found = true;
						break;
					}
				}
				scanner.close();
			} catch (Throwable throwable) {
				try {
					scanner.close();
				} catch (Throwable throwable1) {
					throwable.addSuppressed(throwable1);
				}
				throw throwable;
			}
		} catch (Throwable e) {
			return false;
		}
		if (!found)
			return false;
		try {
			Class<?> clazz = Class.forName("java.lang.UNIXProcess");
			Method destroyProcess = clazz.getDeclaredMethod("destroyProcess", new Class[] { int.class, boolean.class });
			destroyProcess.setAccessible(true);
			boolean force = false;
			destroyProcess.invoke((Object) null, new Object[] { Integer.valueOf(this.pid), Boolean.valueOf(force) });
			return true;
		} catch (Throwable e) {
			return false;
		}
	}
}
